package com.xindaoapp.happypet.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rockerhieu.emojicon.EmojiconHandler;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.EmptyAdapter;
import com.xindaoapp.happypet.adapter.FaceAdapter;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.BaseEntity;
import com.xindaoapp.happypet.bean.CommentInfo;
import com.xindaoapp.happypet.bean.PostLandlordInfo;
import com.xindaoapp.happypet.bean.PostLayerInfo;
import com.xindaoapp.happypet.entry.PostCommentInfos;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.Expressions;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.InputRegular;
import com.xindaoapp.happypet.utils.PostContentManager;

/**
 * 评论页面
 * 
 * 传参：
 * 
 * 楼层信息
 * 
 * @author xindaoapp
 * 
 */
public class CommentActivity extends BaseActivity implements OnClickListener {
    private PullToRefreshListView mPullToRefreshListView;
    private View vFaceButton;
    private View vSendMessage;
    private EditText vPostContent;
    /** 图片viewpager区域 */
    private ViewPager vFaceViewPager;
    /** 小点区域 */
    private LinearLayout vPointContainer;
    private View vPackUpComment;
    private View vSendContainer;
    private View vFaceContainer;

    private PostLayerInfo mPostLayerInfo;
    private PostLandlordInfo mPostLandlordInfo;
    private String mPostContent = "";

    private CommentInfo mCommentInfo;
    private CommentAdapter mAdapter;
    private String mPostTid;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_post_detail_comment;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mPostTid = getIntent().getStringExtra(Constants.KEY_POST_TID);
        mPostLandlordInfo =
                (PostLandlordInfo) getIntent().getSerializableExtra(Constants.KEY_LANDLORD_INFO);
        mPostLayerInfo = (PostLayerInfo) getIntent().getSerializableExtra(Constants.KEY_LAYER_INFO);
        mCommentInfo = (CommentInfo) getIntent().getSerializableExtra(Constants.KEY_COMMENT_INFO);

        vFaceContainer = findViewById(R.id.face);
        vSendContainer = findViewById(R.id.v_send);
        vPackUpComment = findViewById(R.id.packup_comment);
        vFaceButton = findViewById(R.id.face_button);
        vSendMessage = findViewById(R.id.send);
        vPointContainer = (LinearLayout) findViewById(R.id.page_select);
        vFaceViewPager = (ViewPager) findViewById(R.id.viewpager);
        mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                onLoadDatas();
            }
        });
        vPostContent = (EditText) findViewById(R.id.content);
        mPullToRefreshListView.getRefreshableView().addHeaderView(getHeaderView(mPostLayerInfo));
        if (mPostLayerInfo.commentarray.size() == 0) {
            mPullToRefreshListView.setAdapter(new EmptyAdapter(this));
        } else {
            mPullToRefreshListView
                    .setAdapter(mAdapter =
                            new CommentAdapter(getBaseContext(), mPostLayerInfo.commentarray,
                                    Constants.PAGE_SIZE, R.layout.list_item_comment,
                                    R.layout.item_loading));
            mPullToRefreshListView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switchState(STATE.INPUTSTATE);
                }
            });
        }

        vPostContent.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                vFaceContainer.setVisibility(View.GONE);
                return false;
            }
        });
        vPostContent.addTextChangedListener(mContentTextWatcher);
        vPostContent.clearFocus();
        initFaceView();


        if (mCommentInfo != null || getIntent().hasExtra(Constants.KEY_MODE_LOOK_COMMENT)) {
            HappyPetApplication.mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    switchState(STATE.INPUTSTATE);
                }
            }, 300);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (vSendContainer.getVisibility() == View.VISIBLE) {
                switchState(STATE.NONE);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private final TextWatcher mContentTextWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s.toString())) {
                mPostContent = "";
                return;
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

        @Override
        public void afterTextChanged(Editable arg0) {
            mPostContent = EmojiconHandler.getMEmojiCode();
        }

    };

    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
        getMoccaApi().getComments(mPostLayerInfo.pid, Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                new IRequest<PostCommentInfos>() {

                    @Override
                    public void request(PostCommentInfos t) {
                        if (t != null && t.array.size() > 0) {
                            mPullToRefreshListView.setAdapter(mAdapter =
                                    new CommentAdapter(getBaseContext(), t.array,
                                            Constants.PAGE_SIZE, R.layout.list_item_comment,
                                            R.layout.item_loading));
                        }
                        mPullToRefreshListView.onRefreshComplete();
                    }
                });
    }

    private View getHeaderView(PostLayerInfo value) {
        View convertView =
                View.inflate(getBaseContext(), R.layout.list_item_post_detail_layer, null);
        ViewHolder holder = (ViewHolder) convertView.getTag();
        if (null == holder) {
            holder = new ViewHolder();
            holder.logoLandlord = (ImageView) convertView.findViewById(R.id.logo_landlord);
            holder.logoAdmin = (ImageView) convertView.findViewById(R.id.logo_manager);
            holder.icon = (ImageView) convertView.findViewById(R.id.user_icon);
            holder.username = (TextView) convertView.findViewById(R.id.user_name);
            holder.time = (TextView) convertView.findViewById(R.id.time);
            holder.container = (LinearLayout) convertView.findViewById(R.id.container);
            holder.tools = convertView.findViewById(R.id.tools);
            holder.commentLine = convertView.findViewById(R.id.comment_line);
            holder.commentListView =
                    (LinearLayout) convertView.findViewById(R.id.comment_container);
            holder.examineMoreComment =
                    (TextView) convertView.findViewById(R.id.examine_more_comment);
            holder.reply = convertView.findViewById(R.id.reply);
            holder.popTools = convertView.findViewById(R.id.pop_tools);
            convertView.setTag(holder);
        }

        ImageLoader.getInstance().displayImage(value.userface, holder.icon);
        holder.username.setText(value.author);
        holder.time.setText(String.format("第%s楼  %s", value.position,
                CommonUtil.formatTime2(value.addtime)));

        // holder.commentLine.setVisibility(View.GONE);
        holder.commentListView.setVisibility(View.GONE);

        final View reply = holder.reply;
        final View popTools = holder.popTools;
        holder.tools.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                popTools.setVisibility(View.VISIBLE);
                reply.setVisibility(View.VISIBLE);
                reply.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 评论楼层主
                        popTools.setVisibility(View.GONE);
                        mCommentInfo = null;
                        switchState(STATE.INPUTSTATE);
                    }
                });
            }
        });

        holder.reply.setVisibility(View.GONE);


        holder.container.removeAllViews();

        setPersionPermission(holder.logoAdmin, value.member_groupid);
        setLandlordLogo(holder.logoLandlord, value.authorid);
        holder.examineMoreComment.setVisibility(View.GONE);
        new PostContentManager(this, mPostTid).parsePostContainer(holder.container, value.message,
                -1);
        return convertView;
    }

    class ViewHolder {
        ImageView icon;
        TextView username;
        /** 发表时间 */
        TextView time;
        /** 内容区域 */
        LinearLayout container;
        LinearLayout commentListView;
        View tools;
        View reply;
        TextView examineMoreComment;
        ImageView logoAdmin;
        ImageView logoLandlord;
        View commentLine;
        View popTools;
    }

    /**
     * 设置楼主标志
     * 
     * @param icon
     * @param authorid
     */
    public void setLandlordLogo(ImageView icon, String authorid) {
        if (mPostLandlordInfo.authorid.equals(authorid)) {
            icon.setVisibility(View.VISIBLE);
        } else {
            icon.setVisibility(View.GONE);
        }
    }

    /**
     * 设置管理员标志<br/>
     * 
     * 1为管理员，2为版主，3为版主
     * 
     * @param icon
     * @param memberGroupid
     */
    public void setPersionPermission(ImageView icon, int memberGroupid) {
        if (memberGroupid == 1) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.guanli);
        } else if (memberGroupid == 2) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.banzhu);
        } else if (memberGroupid == 3) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.banzhu);
        } else {
            icon.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        vFaceButton.setOnClickListener(this);
        vPackUpComment.setOnClickListener(this);
        vSendMessage.setOnClickListener(this);
    }

    class CommentAdapter extends XinDaoBaseAdapter<CommentInfo> {

        public CommentAdapter(Context context, List<CommentInfo> iniData, int pageSize, int res,
                int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent,
                final CommentInfo value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (null == holder) {
                holder = new ViewHolder();
                holder.title = (TextView) convertView.findViewById(R.id.title);
                convertView.setTag(holder);
            }
            String time = CommonUtil.formatTime2(value.addtime);
            SpannableStringBuilder ssb =
                    CommonUtil.convetToHtml(CommonUtil.parseEmoji(String.format("%s：%s %s",
                            value.author, value.comment, time)), mContext);
            holder.title.setText(new InputRegular(mContext).parseComment(value.author, time, ssb,
                    new IRequest<Boolean>() {

                        @Override
                        public void request(Boolean t) {
                            if (t) {
                                Intent intent =
                                        new Intent(mContext,
                                                com.xindaoapp.happypet.activity.MainActivity.class);
                                intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                                        UserInfoFragment.class.getCanonicalName());
                                Bundle bundle = new Bundle();
                                bundle.putString(Constants.KEY_UID, value.authorid);
                                bundle.putString(Constants.KEY_USERNAME, value.author);
                                bundle.putString(Constants.KEY_USERFACE, value.userface);
                                intent.putExtra(Constants.KEY_BUNDLE, bundle);
                                startActivity(intent);
                            } else {
                                mCommentInfo = value;
                                switchState(STATE.INPUTSTATE);
                            }
                        }
                    }));

            holder.title.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    mCommentInfo = value;
                    switchState(STATE.INPUTSTATE);
                }
            });
            holder.title.setMovementMethod(LinkMovementMethod.getInstance());

            convertView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    mCommentInfo = value;
                    switchState(STATE.INPUTSTATE);
                }
            });

            return convertView;
        }

        @Override
        public void nextPage(int start, int size,
                final ILoadNextPageData<CommentInfo> iLoadNextPageData) {
            super.nextPage(start, size, iLoadNextPageData);
            getMoccaApi().getComments(mPostLayerInfo.pid, start, size,
                    new IRequest<PostCommentInfos>() {

                        @Override
                        public void request(PostCommentInfos t) {
                            iLoadNextPageData.loadNextPageData(t == null ? null : t.array);
                        }
                    });
        }

        @Override
        public boolean isCheckFirstPage() {
            return false;
        }

        class ViewHolder {
            TextView title;
        }

    }

    /** 初始化表情 */
    private void initFaceView() {
        vPointContainer.removeAllViews();
        View view;
        for (int i = 0; i < 4; i++) {
            // 添加点view对象
            view = new View(this);
            view.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.point_background_postmessage));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15, 15);
            lp.leftMargin = 10;
            view.setLayoutParams(lp);
            view.setEnabled(false);
            vPointContainer.addView(view);
        }
        vFaceViewPager.setAdapter(mPagerAdapter);
        vFaceViewPager.setOnPageChangeListener(mFacePageChangeListener);
        vPointContainer.getChildAt(0).setEnabled(true);
    }

    private final OnPageChangeListener mFacePageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < vPointContainer.getChildCount(); i++) {
                if (arg0 == i) {
                    vPointContainer.getChildAt(i).setEnabled(true);
                } else {
                    vPointContainer.getChildAt(i).setEnabled(false);
                }
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {}

        @Override
        public void onPageScrollStateChanged(int arg0) {}
    };
    private String emojicon = "";

    // 填充ViewPager的数据适配器
    private final PagerAdapter mPagerAdapter = new PagerAdapter() {
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        private int[] getImgs(int position) {
            switch (position) {
                case 0:
                    return Expressions.expressionImgs0;
                case 1:
                    return Expressions.expressionImgs1;
                case 2:
                    return Expressions.expressionImgs2;
                case 3:
                    return Expressions.expressionImgs3;
                default:
                    return null;
            }
        }

        private String[] getImgNames(int position) {
            switch (position) {
                case 0:
                    return Expressions.expressionImgNames0;
                case 1:
                    return Expressions.expressionImgNames1;
                case 2:
                    return Expressions.expressionImgNames2;
                case 3:
                    return Expressions.expressionImgNames3;
                default:
                    return null;
            }
        }

        @Override
        public Object instantiateItem(View container, int position) {
            View view = View.inflate(getBaseContext(), R.layout.layout_post_face, null);
            GridView gridView = (GridView) view.findViewById(R.id.gridview);
            final int[] images = getImgs(position);
            final String[] imageNames = getImgNames(position);
            FaceAdapter adapter = new FaceAdapter(getBaseContext(), images);
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                    Bitmap bitmap = null;
                    bitmap =
                            BitmapFactory.decodeResource(getResources(), images[position
                                    % images.length]);
                    ImageSpan imageSpan = new ImageSpan(getBaseContext(), bitmap);
                    SpannableString spannableString =
                            new SpannableString(imageNames[position].substring(1,
                                    imageNames[position].length() - 1));
                    spannableString.setSpan(imageSpan, 0, imageNames[position].length() - 2,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    // 编辑框设置数据
                    String str = vPostContent.getText().toString();
                    str = CommonUtil.replaceAllKuoHao(str);
                    emojicon = str + imageNames[position];
                    SpannableStringBuilder ssb =
                            CommonUtil.convetToHtml(CommonUtil.parseEmoji(emojicon),
                                    getBaseContext());
                    vPostContent.setText(ssb);
                    vPostContent.setSelection(vPostContent.getText().length());
                }

            });
            ((ViewPager) container).addView(view);
            return view;
        }
    };

    enum STATE {
        NONE, INPUTSTATE, FACE
    }

    private void switchState(STATE state) {
        vPackUpComment.setVisibility(View.GONE);
        vFaceContainer.setVisibility(View.GONE);
        vSendContainer.setVisibility(View.GONE);
        if (STATE.NONE == state) {
            vPackUpComment.setVisibility(View.VISIBLE);
            hideInputMethod();
        } else if (STATE.INPUTSTATE == state) {
            vSendContainer.setVisibility(View.VISIBLE);

            if (mCommentInfo != null) {// 回复楼层主回复
                vPostContent.setText(String.format("回复 %s :", mCommentInfo.author));
            } else {
                vPostContent.setText("");
            }
            vPostContent.requestFocus();
            vPostContent.setFocusable(true);
            vPostContent.setSelection(vPostContent.getText().length());
            showInputMethod();
        } else if (STATE.FACE == state) {
            vSendContainer.setVisibility(View.VISIBLE);
            vFaceContainer.setVisibility(View.VISIBLE);
        }
    }

    public void hideInputMethod() {
        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }

    private void showInputMethod() {
        // 打开软键盘
        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.RESULT_UNCHANGED_HIDDEN);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.face_button:
                hideInputMethod();
                HappyPetApplication.mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {}
                }, 200);
                switchState(STATE.FACE);
                break;
            case R.id.send:
                if (!UserState.isLogged(CommentActivity.this)) {
                    return;
                }
                if (!TextUtils.isEmpty(mPostContent)) {
                    switchState(STATE.NONE);
                    send();
                } else {
                    Toast.makeText(getBaseContext(), "回复内容不能为空！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.packup_comment:
                finish();
                break;

            default:
                break;
        }
    }

    private void send() {
        getMoccaApi().commentLayer(mPostLandlordInfo.tid, mPostLayerInfo.pid, mPostContent,
                mCommentInfo == null ? "0" : mCommentInfo.authorid, new IRequest<BaseEntity>() {

                    @Override
                    public void request(BaseEntity t) {}
                });
        CommentInfo info = new CommentInfo();
        info.addtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        info.author = UserState.getUser().username;
        info.userface = UserState.getUser().userface;
        info.authorid = UserState.getUserUid();
        info.comment = mPostContent;
        if (mAdapter == null) {
            List<CommentInfo> list = new ArrayList<CommentInfo>();
            list.add(info);
            mPullToRefreshListView.setAdapter(mAdapter =
                    new CommentAdapter(getBaseContext(), list, Constants.PAGE_SIZE,
                            R.layout.list_item_comment, R.layout.item_loading));
        } else {
            mAdapter.getResult().add(0, info);
            mAdapter.notifyDataSetChanged();
        }
        vPostContent.setText("");
    }

}
